﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CommonLibrary;
using CommonLibrary.BLL;
using CommonLibrary.Model;

namespace SmsSeries
{
    public partial class frmMain : Form
    {
        #region 变量

        /// <summary>
        /// 用户信息
        /// </summary>
        List<UserInfoInfo> userInfoInfos=new List<UserInfoInfo>();

        /// <summary>
        /// 日志信息
        /// </summary>
        List<EventLogInfo> eventLogInfos=new List<EventLogInfo>();

        /// <summary>
        /// 正在发送信息
        /// </summary>
        List<EventLogInfo> eventLogSendingInfos = new List<EventLogInfo>();

        /// <summary>
        /// 等待发送信息
        /// </summary>
        List<EventLogInfo> eventLogWaitInfos = new List<EventLogInfo>();

        /// <summary>
        /// 配置信息
        /// </summary>
        List<ComConfigInfo> comConfigInfos=new List<ComConfigInfo>();

        /// <summary>
        /// 选中的节点
        /// </summary>
        private TreeNode SelectNode;

        private bool isCancel = true;

        #endregion

        #region 控件事件

        // 构造函数
        public frmMain()
        {
            InitializeComponent();
        }

        //窗体加载
        private void frmMain_Load(object sender, EventArgs e)
        {
            dtStartTime.Value = DateTime.Now.Date;

            dtEndTime.Value = DateTime.Now.Date;
            dtEndTime.Value = DateTime.Now.Date.AddHours(23).AddMinutes(59).AddSeconds(59);

            userInfoInfos = UserInfo.GetList("");
            eventLogInfos = EventLog.GetList("");
            comConfigInfos = ComConfig.GetList("");

            //this.userInfoTableAdapter.Fill(this.smsSeriesDataSet.UserInfo);
            //this.eventLogTableAdapter.Fill(this.smsSeriesDataSet.EventLog);

            AddSMSEvent();              //添加短信控件事件

            tvMenu.ExpandAll();
            TreeNode[] treeNodes = tvMenu.Nodes.Find("AllUsers", true);
            tvMenu.SelectedNode = treeNodes[0];
            //TreeNode root = new TreeNode();
            //root.Expand();
            //TreeNode tn = new TreeNode();
            //root.Text = "短信服务器";
            //tn.Text = "发送记录";
            //root.Nodes.Add(tn);
            //tvMenu.Nodes.Add(root);
        }

        //清除日志
        private void tsbClearLog_Click(object sender, EventArgs e)
        {
            EventLog.DeleteAll();
            //eventLogTableAdapter.DeleteAll();
            eventLogInfos = EventLog.GetList("");
            LoadNode(SelectNode);
            //LoadEventLogListView(eventLogInfos);
            //eventLogTableAdapter.Fill(smsSeriesDataSet.EventLog);
        }

        //串口配置
        private void tsbOption_Click(object sender, EventArgs e)
        {
            frmComOption frm = new frmComOption();
            frm.ShowDialog();

            if (SelectNode != null && SelectNode.Name == "ComState")
            {
                LoadNode(SelectNode);
            }
        }

        //选中Node
        private void tvMenu_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if(e.Node.Name=="SmsSended" | e.Node.Name=="SmsFailed" | e.Node.Name=="SendedSuccess" | e.Node.Name=="SendedFailed")
            {
                pnlSearch.Visible = true;
            }
            else
            {
                pnlSearch.Visible = false;
            }
            tsslStatus.Text = e.Node.Text;

            SelectNode = e.Node;
            LoadNode(e.Node);
        }

        //加载Node
        void LoadNode(TreeNode node)
        {
            if (node.Name == "ComState")
            {
                comConfigInfos = ComConfig.GetList("");
                LoadComConfigListView(comConfigInfos);
            }
            else if (node.Name == "AllUsers")
            {
                userInfoInfos = UserInfo.GetList("");
                LoadUserInfoListView(userInfoInfos, 4);
            }
            else if (node.Name == "AvailableUsers")
            {
                userInfoInfos = UserInfo.GetList("");

                List<UserInfoInfo> _userInfoInfos = userInfoInfos.Where(o => o.StartTime <= DateTime.Now && o.EndTime >= DateTime.Now).ToList();

                LoadUserInfoListView(_userInfoInfos, 5);
            }
            else if (node.Name == "ExpiredUsers")
            {
                userInfoInfos = UserInfo.GetList("");

                List<UserInfoInfo> _userInfoInfos = userInfoInfos.Where(o => o.StartTime > DateTime.Now || o.EndTime < DateTime.Now).ToList();

                LoadUserInfoListView(_userInfoInfos, 6);
            }
            else if (node.Name == "Sending")
            {
                LoadEventLogListView(eventLogSendingInfos, 0);
            }
            else if (node.Name == "WaitSend")
            {
                LoadEventLogListView(eventLogWaitInfos, 1);
            }
            else if (node.Name == "SendedSuccess")
            {
                eventLogInfos = EventLog.GetList("");

                List<EventLogInfo> _eventLogInfos = eventLogInfos.Where(o => o.IsSuccess == true
                    && o.HappenTime >= dtStartTime.Value
                    && o.HappenTime <= dtEndTime.Value).ToList();

                LoadEventLogListView(_eventLogInfos, 2);
            }
            else if (node.Name == "SendedFailed")
            {
                eventLogInfos = EventLog.GetList("");

                List<EventLogInfo> _eventLogInfos = eventLogInfos.Where(o => o.IsSuccess == false
                    && o.HappenTime >= dtStartTime.Value
                    && o.HappenTime <= dtEndTime.Value).ToList();

                LoadEventLogListView(_eventLogInfos, 3);
            }
            else if (node.Name == "SmsFailed")
            {
                List<SentRecordInfo> _sentRecordInfos = SentRecord.GetList("");
                _sentRecordInfos =
                    _sentRecordInfos.Where(o => o.SentStatus != (int) Data.StateEnum.SendedSuccess
                    && o.SentTime >= dtStartTime.Value
                    && o.SentTime <= dtEndTime.Value).ToList();

                LoadSentRecordListListView(_sentRecordInfos, 3);
            }
            else if (node.Name == "SmsSended")
            {
                List<SentRecordInfo> _sentRecordInfos = SentRecord.GetList("");
                _sentRecordInfos =
                    _sentRecordInfos.Where(o => o.SentStatus == (int)Data.StateEnum.SendedSuccess
                    && o.SentTime >= dtStartTime.Value
                    && o.SentTime <= dtEndTime.Value).ToList();

                LoadSentRecordListListView(_sentRecordInfos, 2);
            }
        }

        //退出
        private void tsbQuit_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("请确认是否要退出？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                System.Environment.Exit(0);
            }
        }

        //新增用户
        private void tsbAddUser_Click(object sender, EventArgs e)
        {
            frmUser frmuser = new frmUser();
            frmuser.isUpdate = false;
            frmuser.ShowDialog();

            if (SelectNode != null && SelectNode.Name == "AllUsers" || SelectNode.Name == "AvailableUsers" || SelectNode.Name == "ExpiredUsers")
            {
                LoadNode(SelectNode);
            }
        }

        //用户更新
        private void tsmiEditUser_Click(object sender, EventArgs e)
        {
            frmUser frmuser = new frmUser();
            frmuser.isUpdate = true;
            frmuser._UserInfoInfo = (UserInfoInfo)lvData.Items[lvData.SelectedItems[0].SubItems[0].Text].Tag;
            frmuser.ShowDialog();

            if (SelectNode.Name == "AllUsers" || SelectNode.Name == "AvailableUsers" || SelectNode.Name == "ExpiredUsers")
            {
                LoadNode(SelectNode);
            }
        }

        //用户删除
        private void tsmiDeleteUser_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("请确认是否要删除该用户？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                UserInfoInfo userInfoInfo = (UserInfoInfo)lvData.Items[lvData.SelectedItems[0].SubItems[0].Text].Tag;
                UserInfo.Delete(userInfoInfo.UserID);

                if (SelectNode.Name == "AllUsers" || SelectNode.Name == "AvailableUsers" || SelectNode.Name == "ExpiredUsers")
                {
                    LoadNode(SelectNode);
                }
            }
        }

        //右键使能
        private void cmsUser_Opening(object sender, CancelEventArgs e)
        {
            if (lvData.SelectedItems.Count > 0)
            {
                cmsUser.Enabled = true;
            }
            else
            {
                cmsUser.Enabled = false;
            }
        }

        //帮助
        private void tsbHelp_Click(object sender, EventArgs e)
        {
            frmAbout frm = new frmAbout();
            frm.ShowDialog();
        }

        //开始时间改变
        private void dtStartTime_ValueChanged(object sender, EventArgs e)
        {
            SearchList();
        }

        void SearchList()
        {
            if (SelectNode != null && SelectNode.Name == "SmsSended")
            {
                List<SentRecordInfo> _sentRecordInfos = SentRecord.GetList("");
                _sentRecordInfos =
                    _sentRecordInfos.Where(o => o.SentStatus == (int)Data.StateEnum.SendedSuccess
                    && o.SentTime >= dtStartTime.Value
                    && o.SentTime <= dtEndTime.Value).ToList();

                LoadSentRecordListListView(_sentRecordInfos, 2);
            }
            else if (SelectNode != null && SelectNode.Name == "SmsFailed")
            {
                List<SentRecordInfo> _sentRecordInfos = SentRecord.GetList("");
                _sentRecordInfos =
                    _sentRecordInfos.Where(o => o.SentStatus != (int)Data.StateEnum.SendedSuccess
                    && o.SentTime >= dtStartTime.Value
                    && o.SentTime <= dtEndTime.Value).ToList();

                LoadSentRecordListListView(_sentRecordInfos, 3);
            }
            else if (SelectNode != null && SelectNode.Name == "SendedSuccess")
            {
                eventLogInfos = EventLog.GetList("");

                List<EventLogInfo> _eventLogInfos = eventLogInfos.Where(o => o.IsSuccess == true
                     && o.HappenTime >= dtStartTime.Value
                    && o.HappenTime <= dtEndTime.Value).ToList();

                LoadEventLogListView(_eventLogInfos, 2);
            }
            else if (SelectNode != null && SelectNode.Name == "SendedFailed")
            {
                eventLogInfos = EventLog.GetList("");

                List<EventLogInfo> _eventLogInfos = eventLogInfos.Where(o => o.IsSuccess == false
                     && o.HappenTime >= dtStartTime.Value
                    && o.HappenTime <= dtEndTime.Value).ToList();

                LoadEventLogListView(_eventLogInfos, 3);
            }
        }

        //结束时间改变
        private void dtEndTime_ValueChanged(object sender, EventArgs e)
        {
            SearchList();
        }

        //测试发送
        private void tsbSendMsg_Click(object sender, EventArgs e)
        {
            frmSendMsg frm = new frmSendMsg();
            frm.ShowDialog();
        }

        //打开
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.Visible == false)
            {
                this.Show();
            }
            else
            {
                Close();
            }
        }

        //关闭
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("请确认是否要退出？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                isCancel = false;
                System.Environment.Exit(0);
            }
        }

        //关闭前
        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = isCancel;

            this.Hide();
        }

        //任务栏菜单打开前
        private void cmsTask_Opening(object sender, CancelEventArgs e)
        {
            if (this.Visible)
            {
                openToolStripMenuItem.Text = "隐藏";
            }
            else
            {
                openToolStripMenuItem.Text = "打开";
            }
        }

        //任务栏双击
        private void niTask_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                if (this.Visible)
                {
                    this.Hide();
                }
                else
                {
                    this.Show();
                }
            }
        }

        #endregion

        #region 方法

        /// <summary>
        /// 加载发送日志
        /// </summary>
        /// <param name="_eventLogInfos">发送日志</param>
        void LoadEventLogListView(List<EventLogInfo> _eventLogInfos,int imageIndex)
        {
            lvData.Clear();

            //添加标头
            ColumnHeader title = new ColumnHeader(); 
            title.Text = "编号"; 
            title.Width = 50; 
            this.lvData.Columns.Add(title);

            title = new ColumnHeader();
            title.Text = "时间";
            title.Width = 130;
            this.lvData.Columns.Add(title);

            title = new ColumnHeader(); 
            title.Text = "端口";
            title.Width = 100;
            this.lvData.Columns.Add(title);

            title = new ColumnHeader();
            title.Text = "事件";
            title.Width = 600;
            this.lvData.Columns.Add(title);

            string key;
            lvData.BeginUpdate();

            _eventLogInfos = _eventLogInfos.OrderBy(o => o.LogID).ToList();

            try
            {
                foreach (EventLogInfo eventLogInfo in _eventLogInfos)
                {
                    key = eventLogInfo.LogID.ToString();
                    lvData.Items.Add(key, key, imageIndex);
                    lvData.Items[key].SubItems.Add(eventLogInfo.HappenTime.ToString());
                    lvData.Items[key].SubItems.Add(eventLogInfo.CommPort.ToString());
                    lvData.Items[key].SubItems.Add(eventLogInfo.Description);
                    lvData.Items[key].SubItems.Add(key);
                }
            }
            catch (InvalidOperationException)
            {
                lvData.EndUpdate();
                return;
                
            }
           
            lvData.EndUpdate();
            lvData.ContextMenuStrip = null;
        }

        /// <summary>
        /// 加载串口配置
        /// </summary>
        /// <param name="_comConfigInfos">配置</param>
        void LoadComConfigListView(List<ComConfigInfo> _comConfigInfos)
        {
            lvData.Clear();

            //添加标头
            ColumnHeader title = new ColumnHeader();
            title.Text = "编号";
            title.Width = 50;
            this.lvData.Columns.Add(title);

            title = new ColumnHeader();
            title.Text = "端口号";
            title.Width = 100;
            this.lvData.Columns.Add(title);

            title = new ColumnHeader();
            title.Text = "端口属性";
            title.Width = 130;
            this.lvData.Columns.Add(title);

            title = new ColumnHeader();
            title.Text = "电话号码";
            title.Width = 100;
            this.lvData.Columns.Add(title);

            title = new ColumnHeader();
            title.Text = "限制数量";
            title.Width = 100;
            this.lvData.Columns.Add(title);

            title = new ColumnHeader();
            title.Text = "已发数量";
            title.Width = 100;
            this.lvData.Columns.Add(title);

            title = new ColumnHeader();
            title.Text = "是否启用";
            title.Width = 600;
            this.lvData.Columns.Add(title);

            string key;
            lvData.BeginUpdate();

            _comConfigInfos = _comConfigInfos.OrderBy(o => o.ComID).ToList();

            foreach (ComConfigInfo comConfigInfo in _comConfigInfos)
            {
                key = comConfigInfo.ComID.ToString();
                lvData.Items.Add(key, key,7);
                lvData.Items[key].SubItems.Add(comConfigInfo.ComNo.ToString());
                lvData.Items[key].SubItems.Add(comConfigInfo.ComProperty);
                lvData.Items[key].SubItems.Add(comConfigInfo.TelNnumber);
                lvData.Items[key].SubItems.Add(comConfigInfo.LimitedCount.ToString());
                lvData.Items[key].SubItems.Add(comConfigInfo.SendedCount.ToString());
                lvData.Items[key].SubItems.Add(comConfigInfo.Enabled.ToString());

                lvData.Items[key].SubItems.Add(key);
            }

            lvData.EndUpdate();
            lvData.ContextMenuStrip = null;
        }

        /// <summary>
        /// 加载用户信息
        /// </summary>
        /// <param name="_comConfigInfos">配置</param>
        void LoadUserInfoListView(List<UserInfoInfo> _userInfoInfos,int imageIndex)
        {
            lvData.Clear();

            //添加标头
            ColumnHeader title = new ColumnHeader();
            title.Text = "编号";
            title.Width = 50;
            this.lvData.Columns.Add(title);

            title = new ColumnHeader();
            title.Text = "用户名";
            title.Width = 100;
            this.lvData.Columns.Add(title);

            title = new ColumnHeader();
            title.Text = "省编号";
            title.Width = 100;
            this.lvData.Columns.Add(title);

            title = new ColumnHeader();
            title.Text = "市编号";
            title.Width = 100;
            this.lvData.Columns.Add(title);

            title = new ColumnHeader();
            title.Text = "开始时间";
            title.Width = 130;
            this.lvData.Columns.Add(title);

            title = new ColumnHeader();
            title.Text = "结束时间";
            title.Width = 130;
            this.lvData.Columns.Add(title);

            title = new ColumnHeader();
            title.Text = "是否被锁定";
            title.Width = 100;
            this.lvData.Columns.Add(title);

            title = new ColumnHeader();
            title.Text = "备注";
            title.Width = 600;
            this.lvData.Columns.Add(title);

            string key;
            lvData.BeginUpdate();

            _userInfoInfos = _userInfoInfos.OrderBy(o => o.UserID).ToList();

            foreach (UserInfoInfo userInfoInfo in _userInfoInfos)
            {
                key = userInfoInfo.UserID.ToString();
                lvData.Items.Add(key, key, imageIndex);
                lvData.Items[key].Tag = userInfoInfo;
                lvData.Items[key].SubItems.Add(userInfoInfo.UserName);
                lvData.Items[key].SubItems.Add(userInfoInfo.ProvinceID.ToString());
                lvData.Items[key].SubItems.Add(userInfoInfo.CityID.ToString());
                lvData.Items[key].SubItems.Add(userInfoInfo.StartTime.ToShortDateString());
                lvData.Items[key].SubItems.Add(userInfoInfo.EndTime.ToShortDateString());
                lvData.Items[key].SubItems.Add(userInfoInfo.Locked.ToString());
                lvData.Items[key].SubItems.Add(userInfoInfo.Description.ToString());

                lvData.Items[key].SubItems.Add(key);
            }

            lvData.EndUpdate();

            lvData.ContextMenuStrip = this.cmsUser;
        }

        /// <summary>
        /// 加载发送记录信息
        /// </summary>
        /// <param name="sentRecordInfos"></param>
        /// <param name="imageIndex">发送记录</param>
        void LoadSentRecordListListView(List<SentRecordInfo> sentRecordInfos,int imageIndex)
        {
            lvData.Clear();

            //添加标头
            ColumnHeader title = new ColumnHeader();
            title.Text = "编号";
            title.Width = 50;
            this.lvData.Columns.Add(title);

            title = new ColumnHeader();
            title.Text = "发送时间";
            title.Width = 130;
            this.lvData.Columns.Add(title);

            title = new ColumnHeader();
            title.Text = "任务编号";
            title.Width = 70;
            this.lvData.Columns.Add(title);

            title = new ColumnHeader();
            title.Text = "分条索引";
            title.Width = 70;
            this.lvData.Columns.Add(title);

            title = new ColumnHeader();
            title.Text = "目标号码";
            title.Width = 100;
            this.lvData.Columns.Add(title);

            title = new ColumnHeader();
            title.Text = "短信内容";
            title.Width = 600;
            this.lvData.Columns.Add(title);

            title = new ColumnHeader();
            title.Text = "发送状态";
            title.Width = 130;
            this.lvData.Columns.Add(title);

            title = new ColumnHeader();
            title.Text = "端口号";
            title.Width = 100;
            this.lvData.Columns.Add(title);

            string key;
            lvData.BeginUpdate();

            sentRecordInfos = sentRecordInfos.OrderBy(o => o.MsgID).ToList();

            foreach (SentRecordInfo sentRecordInfo in sentRecordInfos)
            {
                key = sentRecordInfo.MsgID.ToString();
                lvData.Items.Add(key, key, imageIndex);
                lvData.Items[key].SubItems.Add(sentRecordInfo.SentTime.ToString());
                lvData.Items[key].SubItems.Add(sentRecordInfo.TaskID.ToString());
                lvData.Items[key].SubItems.Add(sentRecordInfo.SplitIndex.ToString());
                lvData.Items[key].SubItems.Add(sentRecordInfo.DestTel);
                lvData.Items[key].SubItems.Add(sentRecordInfo.Content);

                string s = "";
                switch ((Data.StateEnum)sentRecordInfo.SentStatus)
                {
                    case Data.StateEnum.MsgExpired:
                        s = "消息过期";
                        break;
                    case Data.StateEnum.SendedFalse:
                        s = "发送失败";
                        break;
                    case Data.StateEnum.SendedSuccess:
                        s = "发送成功";
                        break;
                    case Data.StateEnum.Sending:
                        s = "正在发送";
                        break;
                    case Data.StateEnum.UserExpired:
                        s = "用户过期";
                        break;
                    case Data.StateEnum.UserIsLocked:
                        s = "用户被锁定";
                        break;
                    case Data.StateEnum.UserNotExist:
                        s = "用户不存在";
                        break;
                    case Data.StateEnum.WaitSend:
                        s = "待发送";
                        break;
                }

                lvData.Items[key].SubItems.Add(s);
                lvData.Items[key].SubItems.Add(sentRecordInfo.CommPort.ToString());

                lvData.Items[key].SubItems.Add(key);
            }

            lvData.EndUpdate();
        }

        #endregion
    }
}
